package com.sl.au.service.impl;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.sl.au.entity.Attachment;
import com.sl.au.entity.Chance;
import com.sl.au.entity.ConfigDetailForCRM;
import com.sl.au.entity.Customer;
import com.sl.au.entity.CustomerMailingInfo;
import com.sl.au.entity.CustomerPayInfo;
import com.sl.au.entity.ExdeBeforeContractWGDetail;
import com.sl.au.entity.Quote;
import com.sl.au.entity.QuoteDevice;
import com.sl.au.entity.QuoteReplacement;
import com.sl.au.entity.User;
import com.sl.au.repository.CustomerMailingInfoRepository;
import com.sl.au.repository.CustomerRepository;
import com.sl.au.repository.EXDECustomerPayInfoRepository;
import com.sl.au.repository.QuoteDeviceRepository;
import com.sl.au.repository.QuoteReplacementRepository;
import com.sl.au.repository.QuoteRepository;
import com.sl.au.service.AttachmentService;
import com.sl.au.service.AuditNodeService;
import com.sl.au.service.DocService;
import com.sl.au.service.InventoryReduceService;
import com.sl.au.service.QuoteForeignService;
import com.sl.au.service.QuoteService;
import com.sl.utils.DataConverter;

@Service("QuoteService")
public class QuoteServiceImpl extends BaseServiceImpl implements QuoteService {

	@Autowired
	QuoteRepository quoteRepository;
	@Autowired
	QuoteForeignService quoteForeignService;
	@Autowired
	InventoryReduceService inventoryReduceService;
	@Autowired
	AuditNodeService auditNodeService;
	@Autowired
	AttachmentService attachmentService;
	@Autowired
	QuoteDeviceRepository quoteDeviceRepository;
	@Autowired
	QuoteReplacementRepository quoteReplacementRepository;
	@Autowired
	CustomerMailingInfoRepository customerMailingInfoRepository;
	@Autowired
	EXDECustomerPayInfoRepository exdeCustomerPayInfoRepository;
	@Autowired
	CustomerRepository customerRepository;
	@Override
	public QuoteRepository getRepository() {
		return this.quoteRepository;
	}

	@Override
	public List<Quote> getQuote(int start, int length, Map<String, String> condition, String orderName, String dir) {
		Page<Quote> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		if (condition.get("dataFilter").equals("所有"))
			pages = quoteRepository.findQuote(condition.get("key"), pageable);
		else if (condition.get("dataFilter").equals("本部门"))
			pages = quoteRepository.findSuperiorPage(condition.get("key"), condition.get("superior"),
					condition.get("userId"), pageable);
		else if (condition.get("dataFilter").equals("本片区"))
			pages = quoteRepository.finAreaPage(condition.get("key"), condition.get("areaId"), condition.get("userId"),
					pageable);
		else
			pages = quoteRepository.findSelfPage(condition.get("key"), condition.get("userId"), pageable);
		
		if(condition.get("state").equals("通过")){
			pages = quoteRepository.findQuote(condition.get("key"),condition.get("superior"), pageable);
		}
		
		List<Attachment>attachments=null;
		List<Quote> quotes = pages.getContent();
		List<Quote> quotes2 = new ArrayList<Quote>();
		for(Quote quote:quotes){
			String parentId=quote.getId();
			attachments=attachmentService.getRepository().findByParentId(parentId);
			if(!attachments.isEmpty()){
				quote.setAttachCount(attachments.size());
			}
			quotes2.add(quote);
		}
		return quotes2;
	}

	@Override
	public long getQuoteCount(Map<String, String> condition) {
		long count = 0;
		if (condition.get("dataFilter").equals("所有"))
			count = quoteRepository.getCountBykey(condition.get("key"));
		else if (condition.get("dataFilter").equals("本部门"))
			count = quoteRepository.findSuperiorCount(condition.get("key"), condition.get("superior"),
					condition.get("userId"));
		else if (condition.get("dataFilter").equals("本片区"))
			count = quoteRepository.findAreaCount(condition.get("key"), condition.get("areaId"),
					condition.get("userId"));
		else
			count = quoteRepository.findSelfCount(condition.get("key"), condition.get("userId"));
		
		if(condition.get("state").equals("通过")){
			count = quoteRepository.findQuoteCount(condition.get("key"),condition.get("superior"));
		}
		
		return count;
	}

	@Override
	public List<QuoteDevice> getQuoteDevice(int start, int length, String quoteId, String orderName, String dir) {
		Page<QuoteDevice> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime","isInventory");
		pages = quoteForeignService.getDeviceRepository().findQuoteDeviceByQuoteId(quoteId, pageable);
		return pages.getContent();
	}


	// 得到其他细目
	@Override
	public List<QuoteReplacement> getQuoteReplacement(int start, int length, String quoteId, String orderName,
			String dir) {
		Page<QuoteReplacement> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.ASC, "indexOrder");
		pages = quoteRepository.findQuoteReplacement(quoteId, pageable);
		return pages.getContent();
	}

	@Override
	public void saveProcessStart(String quoteId, ProcessInstance pInst) {
		Quote quote = quoteRepository.getOne(quoteId);
		if (null == pInst || null == quote)
			return;
		// 如果是重新提交审批，删除原来的审批节点
		auditNodeService.getRepository().deleteByPInstId(quote.getProcessInstId());
		quote.setProcessInstId(pInst.getId());
		quote.setAuditState("已提交");
		quote.setStartDate(new Date());
		this.getRepository().save(quote);

	}

	@Override
	public List<Quote> getQuoteInState(int start, int length, String key, String audit, String superior) {
		Page<Quote> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		pages = quoteRepository.findPassQuote(key, audit, superior, pageable);
		return pages.getContent();
	}

	@Override
	public String genQuoteDocx(String quoteId,String sender) {
		String filename = null;
		DecimalFormat df = new DecimalFormat( "###############0.00 ");
		Quote quote = quoteRepository.findOne(quoteId);
		if (null != quote) {
			Map<String, Object> data = new HashMap<>();
			Map<String, LinkedList<List<String>>> tablesData = new HashMap<>();
			List<QuoteDevice> quoteDevices = quoteForeignService.getDeviceRepository().findQuoteDeviceList(quoteId);
			LinkedList<List<String>> linkedQuotes1 = new LinkedList<>();
			List<String> row1;
			int order1 = 0;
			for (QuoteDevice device : quoteDevices) {
				row1 = new ArrayList<>();
				row1.add((++order1) + "");
				row1.add(device.getProductName());
				row1.add(device.getProductModel());
				row1.add("");
				row1.add(device.getUnit());
				row1.add(device.getNumber()+"");
				row1.add(df.format(device.getUnitPrice()) + "");
				double sum = device.getNumber() * device.getUnitPrice();
				row1.add(df.format(sum) + "");
				linkedQuotes1.add(row1);
			}
			List<QuoteReplacement>quoteReplacements=quoteReplacementRepository.findByQuote_Id(quoteId);
			for(QuoteReplacement quoteReplacement:quoteReplacements){
				row1 = new ArrayList<>();
				row1.add((++order1) + "");
				row1.add(quoteReplacement.getDeviceName());
				row1.add(quoteReplacement.getType());
				row1.add(quoteReplacement.getMaterial());
				row1.add(quoteReplacement.getUnit());
				row1.add(quoteReplacement.getAmount()+"");
				row1.add(df.format(quoteReplacement.getPrice()) + "");
				double sum = quoteReplacement.getAmount() * quoteReplacement.getPrice();
				row1.add(df.format(sum) + "");
				linkedQuotes1.add(row1);
			}
			tablesData.put("q", linkedQuotes1);
			Map<String, String> textData = new HashMap<>();
			textData.put("customerName", quote.getCustomerName());
			textData.put("sender",sender );
			textData.put("userName", quote.getUser().getEmpLogin().getName());
			textData.put("quoteDate", DataConverter.toZnDateYMD(new Date()));
			textData.put("guaranteeMonths", "24");
			textData.put("assumeSum", df.format(quote.getAssumeSum())+"");
			data.put("textData", textData);
			data.put("tablesData", tablesData);
			filename = DocService.genTemplate("报价单模板.docx", data, "报价单");
		}
		return filename;
	}

	@Override
	public List<QuoteDevice> searchQuoteDevicePrice(int start, int length, Map<String, String> condition) {
		Page<QuoteDevice> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		String key = condition.get("key");
		if (condition.get("dataFilter").equals("所有")) {
			pages = quoteDeviceRepository.getQuoteDevice(key, pageable);
		} else if (condition.get("dataFilter").equals("本部门")) {
			if (condition.get("superior").equals("外贸处")) {
				pages = quoteDeviceRepository.getQuoteForeignDevice(condition.get("key"), condition.get("superior"),
						pageable);
			} else {
				pages = quoteDeviceRepository.getQuoteDevice(condition.get("key"), condition.get("superior"), pageable);
			}
		} else if (condition.get("dataFilter").equals("本片区")) {
			if (condition.get("superior").equals("外贸处")) {
				pages = quoteDeviceRepository.getQuoteForeignAreaDevice(condition.get("key"), condition.get("areaId"),
						pageable);
			} else {
				pages = quoteDeviceRepository.getQuoteAreaDevice(condition.get("key"), condition.get("areaId"),
						pageable);
			}
		} else if (condition.get("dataFilter").equals("本人")) {
			if (condition.get("superior").equals("外贸处")) {
				pages = quoteDeviceRepository.getQuoteSelfDevice(condition.get("key"), condition.get("userId"),
						pageable);
			} else {
				pages = quoteDeviceRepository.getQuoteForeignSelfDevice(condition.get("key"), condition.get("userId"),
						pageable);
			}
		}
		return pages.getContent();
	}

	@Override
	public List<QuoteReplacement> searchQuoteReplacePrice(int start, int length, Map<String, String> condition) {
		Page<QuoteReplacement> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime", "deviceName");
		if (condition.get("dataFilter").equals("所有")) {
			pages = quoteDeviceRepository.getQuoteReplace(condition.get("key"), pageable);
		} else if (condition.get("dataFilter").equals("本部门")) {
			if (condition.get("superior").equals("外贸处")) {
				pages = quoteDeviceRepository.getForeignReplace(condition.get("key"), condition.get("superior"),
						pageable);
			} else {
				pages = quoteDeviceRepository.getQuoteReplace(condition.get("key"), condition.get("superior"),
						pageable);
			}
		} else if (condition.get("dataFilter").equals("本片区")) {
			if (condition.get("superior").equals("外贸处")) {
				pages = quoteDeviceRepository.getForeignAreaReplace(condition.get("key"), condition.get("areaId"),
						pageable);
			} else {
				pages = quoteDeviceRepository.getQuoteAreaReplace(condition.get("key"), condition.get("areaId"),
						pageable);
			}
		} else if (condition.get("dataFilter").equals("本人")) {
			if (condition.get("superior").equals("外贸处")) {
				pages = quoteDeviceRepository.getForeignSelfReplace(condition.get("key"), condition.get("userId"),
						pageable);
			} else {
				pages = quoteDeviceRepository.getQuoteSelfReplace(condition.get("key"), condition.get("userId"),
						pageable);
			}
		}
		return pages.getContent();
	}

	@Override
	public long searchQuoteDeviceCount(Map<String, String> condition) {
		long count = 0;
		if (condition.get("dataFilter").equals("所有")) {
			count = quoteDeviceRepository.getQuoteDeviceCount(condition.get("key"));
		} else if (condition.get("dataFilter").equals("本部门")) {
			if (condition.get("superior").equals("外贸处")) {
				count = quoteDeviceRepository.getQuoteDeviceForeignCount(condition.get("key"),
						condition.get("superior"));
			} else {
				count = quoteDeviceRepository.getQuoteDeviceCount(condition.get("key"), condition.get("superior"));
			}
		} else if (condition.get("dataFilter").equals("本片区")) {
			if (condition.get("superior").equals("外贸处")) {
				count = quoteDeviceRepository.getForeignReplaceAreaCount(condition.get("key"), condition.get("areaId"));
			} else {
				count = quoteDeviceRepository.getQuoteDeviceAreaCount(condition.get("key"), condition.get("areaId"));
			}
		} else if (condition.get("dataFilter").equals("本人")) {
			if (condition.get("superior").equals("外贸处")) {
				count = quoteDeviceRepository.getQuoteDeviceForeignSelfCount(condition.get("key"),
						condition.get("userId"));
			} else {
				count = quoteDeviceRepository.getQuoteDeviceSelfCount(condition.get("key"), condition.get("userId"));
			}
		}
		return count;
	}

	@Override
	public long searchQuoteReplaceCount(Map<String, String> condition) {
		long count = 0;
		if (condition.get("dataFilter").equals("所有")) {
			count = quoteDeviceRepository.getQuoteReplaceCount(condition.get("key"));
		} else if (condition.get("dataFilter").equals("本部门")) {
			if (condition.get("superior").equals("外贸处")) {
				count = quoteDeviceRepository.getQuoteDeviceForeignCount(condition.get("key"),
						condition.get("superior"));
			} else {
				count = quoteDeviceRepository.getQuoteDeviceCount(condition.get("key"), condition.get("superior"));
			}
		} else if (condition.get("dataFilter").equals("本片区")) {
			if (condition.get("superior").equals("外贸处")) {
				count = quoteDeviceRepository.getForeignReplaceAreaCount(condition.get("key"), condition.get("areaId"));
			} else {
				count = quoteDeviceRepository.getQuoteDeviceAreaCount(condition.get("key"), condition.get("areaId"));
			}
		} else if (condition.get("dataFilter").equals("本人")) {
			if (condition.get("superior").equals("外贸处")) {
				count = quoteDeviceRepository.getForeignReplaceSelfCount(condition.get("key"), condition.get("userId"));
			} else {
				count = quoteDeviceRepository.getQuoteDeviceSelfCount(condition.get("key"), condition.get("userId"));
			}
		}
		return count;
	}
	
	// 得到其他细目
		@Override
		public List<QuoteReplacement> getQuoteReplacementER(int start, int length, Map<String, String> condition, String orderName,
				String dir) {
			Page<QuoteReplacement> pages = null;
			Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
			pages = quoteRepository.findQuoteReplacementER(condition.get("quoteId"), condition.get("key"), pageable);
			return pages.getContent();
		}

		@Override
		public List<QuoteReplacement> getQuoteReplacementERprice(int start, int length, Map<String, String> condition,
				String orderName, String dir) {
			Page<QuoteReplacement> pages = null;
			Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
			pages = quoteRepository.findQuoteReplacementERprice(condition.get("type"), condition.get("deviceName"), condition.get("material"), condition.get("customerName"), pageable);
			return pages.getContent();
		}

		@Override
		public void saveOtherDevice(QuoteReplacement quoteReplacement, List<QuoteReplacement> quoteReplacements,
				boolean isInit) {
			for(int i=0;i<quoteReplacements.size();i++){
				QuoteReplacement a = quoteReplacements.get(i);
				int b = a.getIndexOrder();
				if(isInit){
					if(b>=quoteReplacement.getIndexOrder())
						a.setIndexOrder(b+1);
				}else{
					QuoteReplacement old = quoteReplacementRepository.findOne(quoteReplacement.getId());
					if(quoteReplacement.getIndexOrder()<old.getIndexOrder()){
						if(i<old.getIndexOrder()-1 && i>=quoteReplacement.getIndexOrder()-1){
							a.setIndexOrder(b+1);
						}
					}else if(quoteReplacement.getIndexOrder()>old.getIndexOrder()){
						if(i>old.getIndexOrder()-1 && i<=quoteReplacement.getIndexOrder()-1){
							a.setIndexOrder(b-1);
						}
					}
				}
				quoteReplacementRepository.save(a);
			}
			quoteReplacementRepository.save(quoteReplacement);
			
		}

		@Override
		public QuoteReplacement getNextOrBeforeOtherDevice(String nowQuoteId, int nowIndex, int isNext) {
			List<QuoteReplacement> quoteReplacements = new ArrayList<QuoteReplacement>();
			if(isNext == 0){//before
				quoteReplacements = quoteReplacementRepository.findBeforeQuoteReplacement(nowQuoteId,nowIndex);
			}else if(isNext == 1){//next
				quoteReplacements = quoteReplacementRepository.findNextQuoteReplacement(nowQuoteId,nowIndex);
			}
			
			if(quoteReplacements != null && quoteReplacements.size() > 0){
				return quoteReplacements.get(0);
			}else{
				return null;
			}
		}

		@Override
		public long[] getNowIndexAndCount(QuoteReplacement quoteReplacement) {
			long[] result = new long[2];
			List<QuoteReplacement> quoteReplacements = new ArrayList<QuoteReplacement>();
			quoteReplacements = quoteReplacementRepository.findBeforeQuoteReplacement(quoteReplacement.getQuote().getId(),quoteReplacement.getIndexOrder());
			if(quoteReplacements!= null){
				result[0] = quoteReplacements.size() + 1;
			}else{
				result[0] = 1;
			}
			long count = quoteRepository.getReplacementCount(quoteReplacement.getQuote().getId());
			result[1] = count;
			return result;
		}

		@Override
		public void reCheckQuoteIndex(String quoteId) {
			List<QuoteReplacement> quoteReplacements  = quoteRepository.findReplacementByQuoteId(quoteId);
			if(quoteReplacements == null || quoteReplacements.size() == 0){
				return;
			}
			int i = 0;
			for(QuoteReplacement page : quoteReplacements){
				page.setIndexOrder(++i);
				quoteReplacementRepository.save(page);
			}
		}

		@Override
		public List<QuoteReplacement> getHisDetails(int start, int length, Map<String, String> condition,
				String orderName, String dir) {
			Pageable pageable=new PageRequest(start/length,length);
			List<QuoteReplacement> list = null;
			list = quoteRepository.getHisDetails(condition.get("key"), condition.get("quoteid"), pageable);
			return list;
		}

		@Override
		public long getHisDetailsCount(Map<String, String> condition) {
			return quoteRepository.getHisDetailsCount(condition.get("key"), condition.get("quoteid"));
		}

		@Override
		public List<Quote> getpagehisquote(int start, int length, Map<String, String> condition, String orderName,
				String dir) {
			Pageable pageable=new PageRequest(start/length,length);
			List<Quote> list = null;
			list = quoteRepository.getpagehisquote(condition.get("key"), pageable);
			return list;
		}

		@Override
		public long getpagehisquoteCount(Map<String, String> condition) {
			return quoteRepository.getpagehisquoteCount(condition.get("key"));
		}

		@Override
		public String genQuoteBJDocx(String quoteId, User user) {
			String filename = null;
			DecimalFormat df = new DecimalFormat( "###############0.00 ");
			Quote quote = quoteRepository.findOne(quoteId);
			Customer customer = customerRepository.findOne(quote.getCustomerId());
			CustomerMailingInfo customerMailingInfo = customerMailingInfoRepository.findByCustomer_IdAndIsDefaultPart(quote.getCustomerId(), 1);
			if(customerMailingInfo == null){
				List<CustomerMailingInfo> lists = customerMailingInfoRepository.findByCustomer_IdByUpdateTimeDESC(quote.getCustomerId());
				if(lists.size()>0){
					customerMailingInfo = lists.get(0);
				}
			}
			CustomerPayInfo customerPayInfo=exdeCustomerPayInfoRepository.findByCustomer_IdAndIsDefaultPart(quote.getCustomerId(), 1);
			if(customerPayInfo == null){
				List<CustomerPayInfo> lists1 = exdeCustomerPayInfoRepository.findByCustomer_IdByUpdateTimeDESC(quote.getCustomerId());
				if(lists1.size()>0){
					customerPayInfo = lists1.get(0);
				}
			}
			if (null != quote) {
				Map<String, Object> data = new HashMap<>();
				Map<String, LinkedList<List<String>>> tablesData = new HashMap<>();
				List<QuoteDevice> quoteDevices = quoteForeignService.getDeviceRepository().findQuoteDeviceList(quoteId);
				LinkedList<List<String>> linkedQuotes1 = new LinkedList<>();
				List<String> row1;
				int order1 = 0;
				double sum = 0;
				for (QuoteDevice device : quoteDevices) {
					row1 = new ArrayList<>();
					row1.add((++order1) + "");
					row1.add(device.getProductName());
					row1.add(device.getProductModel());
					//row1.add("");
					row1.add(device.getUnit());
					row1.add(device.getNumber()+"");
					row1.add(df.format(device.getUnitPrice()) + "");
					double sum1 = device.getNumber() * device.getUnitPrice();
					sum += sum1;
					row1.add(df.format(sum1) + "");
					row1.add(device.getcMemo());
					linkedQuotes1.add(row1);
				}
				List<QuoteReplacement>quoteReplacements=quoteReplacementRepository.findByQuote_Id(quoteId);
				for(QuoteReplacement quoteReplacement:quoteReplacements){
					row1 = new ArrayList<>();
					row1.add((++order1) + "");
					row1.add(quoteReplacement.getDeviceName());
					row1.add(quoteReplacement.getType());
					//row1.add(quoteReplacement.getMaterial());
					row1.add(quoteReplacement.getUnit());
					row1.add(quoteReplacement.getAmount()+"");
					row1.add(df.format(quoteReplacement.getPrice()) + "");
					double sum1 = quoteReplacement.getAmount() * quoteReplacement.getPrice();
					sum += sum1;
					row1.add(df.format(sum1) + "");
					row1.add(quoteReplacement.getMemo());
					linkedQuotes1.add(row1);
				}
				tablesData.put("q", linkedQuotes1);
				Map<String, String> textData = new HashMap<>();
				textData.put("customerName", quote.getCustomerName());
				textData.put("customerpeoName", customer.getcDHDB() + ":" + customer.getcDHPhone());
				if(customerMailingInfo != null){
					textData.put("customerPerson", customerMailingInfo.getPostDelegate() + ":" + customerMailingInfo.getPostPhone() );
					textData.put("customerTel", customerMailingInfo.getPostPhone());
				}
				if(customerPayInfo != null){
					textData.put("customerFax", customerPayInfo.getInvoiceFax());
					textData.put("identification", customerPayInfo.getIdentification());
					textData.put("invoiceAddress", customerPayInfo.getInvoiceAddress());
					textData.put("invoicePhone", customerPayInfo.getInvoicePhone());
					textData.put("invoiceBank", customerPayInfo.getInvoiceBank());
					textData.put("bankAccount", customerPayInfo.getBankAccount());
					textData.put("zipCode", customerPayInfo.getZipCode());
				}
				textData.put("payDate", DataConverter.toZnDateYMD(new Date()));
				textData.put("sum",sum + "" );
				textData.put("sender",user.getName() );
				textData.put("userName", user.getEmpLogin().getName());
				textData.put("userphone", user.getContactType());
				/*textData.put("quoteDate", DataConverter.toZnDateYMD(new Date()));
				textData.put("guaranteeMonths", "24");
				textData.put("assumeSum", df.format(quote.getAssumeSum())+"");*/
				data.put("textData", textData);
				data.put("tablesData", tablesData);
				filename = DocService.genTemplate("备件报价单模板.docx", data, "报价单");
			}
			return filename;
		}

		@Override
		public QuoteReplacementRepository getRepository1() {
			// TODO Auto-generated method stub
			return this.quoteReplacementRepository;
		}

		@Override
		public String genQuoteBJHTDocx(String quoteId, User user) throws Exception {
			String filename = null;
			DecimalFormat df = new DecimalFormat( "###############0.00 ");
			SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd");
			Quote quote = quoteRepository.findOne(quoteId);
			Customer customer = customerRepository.findById(quote.getCustomerId());
			CustomerMailingInfo customerMailingInfo = customerMailingInfoRepository.findByCustomer_IdAndIsDefaultPart(quote.getCustomerId(), 1);
			if(customerMailingInfo == null){
				List<CustomerMailingInfo> lists = customerMailingInfoRepository.findByCustomer_IdByUpdateTimeDESC(quote.getCustomerId());
				if(lists.size()>0){
					customerMailingInfo = lists.get(0);
				}
			}
			CustomerPayInfo customerPayInfo=exdeCustomerPayInfoRepository.findByCustomer_IdAndIsDefaultPart(quote.getCustomerId(), 1);
			if(customerPayInfo == null){
				List<CustomerPayInfo> lists1 = exdeCustomerPayInfoRepository.findByCustomer_IdByUpdateTimeDESC(quote.getCustomerId());
				if(lists1.size()>0){
					customerPayInfo = lists1.get(0);
				}
				
			}
			if (null != quote) {
				Map<String, Object> data = new HashMap<>();
				Map<String, LinkedList<List<String>>> tablesData = new HashMap<>();
				//List<QuoteDevice> quoteDevices = quoteForeignService.getDeviceRepository().findQuoteDeviceList(quoteId);
				//LinkedList<List<String>> linkedQuotes1 = new LinkedList<>();
				List<String> row1;
				//int order1 = 0;
				double sum = 0;
				/*for (QuoteDevice device : quoteDevices) {
					row1 = new ArrayList<>();
					row1.add((++order1) + "");
					row1.add(device.getProductName());
					row1.add(device.getProductModel());
					//row1.add("");
					row1.add(device.getUnit());
					row1.add(device.getNumber()+"");
					row1.add(df.format(device.getUnitPrice()) + "");
					double sum1 = device.getNumber() * device.getUnitPrice();
					sum += sum1;
					row1.add(df.format(sum1) + "");
					row1.add(device.getcMemo());
					linkedQuotes1.add(row1);
				}*/
				List<QuoteReplacement>quoteReplacements=quoteReplacementRepository.findByQuote_Id(quoteId);
				LinkedList<List<String>> linkedQuotes1 = new LinkedList<>();
				for(QuoteReplacement quoteReplacement:quoteReplacements){
					row1 = new ArrayList<>();
					//row1.add((++order1) + "");
					row1.add(quoteReplacement.getDeviceName());
					row1.add(quoteReplacement.getType());
					//row1.add(quoteReplacement.getMaterial());
					row1.add(quoteReplacement.getUnit());
					row1.add(quoteReplacement.getAmount()+"");
					row1.add(df.format(quoteReplacement.getPrice()) + "");
					double sum1 = quoteReplacement.getAmount() * quoteReplacement.getPrice();
					sum += sum1;
					row1.add(df.format(sum1) + "");
					row1.add(quoteReplacement.getMemo());
					linkedQuotes1.add(row1);
				}
				//tablesData.put("q", linkedQuotes1);
				tablesData.put("q", linkedQuotes1);
				Map<String, String> textData = new HashMap<>();
				//textData.put("customerPerson", customerMailingInfo.getPostDelegate());
				//textData.put("customerTel", customerMailingInfo.getPostPhone());
				textData.put("customername", quote.getCustomerName());
				if(customerPayInfo != null){
					textData.put("cDHPhone", customerPayInfo.getInvoicePhone());
					textData.put("address", customerPayInfo.getInvoiceAddress());
					textData.put("invoiceBank", customerPayInfo.getInvoiceBank());
					textData.put("bankAccount", customerPayInfo.getBankAccount());
					textData.put("identification", customerPayInfo.getIdentification());
					textData.put("invoiceFax", customerPayInfo.getInvoiceFax());
					textData.put("zipCode", customerPayInfo.getZipCode());
				}
				//textData.put("invoicePhone", customerPayInfo.getInvoicePhone());
				//textData.put("zipCode", customerPayInfo.getZipCode());
				textData.put("payDate", format0.format(new Date()));
				//textData.put("customerName", quote.getCustomerName());
				//textData.put("payDate", DataConverter.toZnDateYMD(new Date()));
				textData.put("sum",sum + "" );
				String htzj = arabNumToChineseRMB(sum);
				textData.put("sum1",htzj);
				/*textData.put("sender",sender );
				textData.put("userName", quote.getUser().getEmpLogin().getName());
				textData.put("quoteDate", DataConverter.toZnDateYMD(new Date()));
				textData.put("guaranteeMonths", "24");
				textData.put("assumeSum", df.format(quote.getAssumeSum())+"");*/
				data.put("textData", textData);
				data.put("tablesData", tablesData);
				filename = DocService.genTemplate("工矿产品购销合同.docx", data, "工矿产品购销合同");
			}
			return filename;
		}
		
		private static final char [] ChineseNum ={'零','壹','贰','叁','肆','伍','陆','柒','捌','玖'};  
		private static final char [] ChineseUnit={'里','分','角','元','拾','佰','仟','万','拾','佰','仟','亿','拾','佰','仟'};  
		  
		/** 
		 * 返回关于钱的中文式大写数字,支仅持到亿 
		 * @throws Exception  
		 * */  
		private static String arabNumToChineseRMB(String moneyNum) throws Exception{  
		    String res="";  
		    int i=3;  
		    int len=moneyNum.length();  
		    if(len>12){  
		        throw new Exception("Number too large!");  
		    }  
		    if("0".equals(moneyNum))  
		        return "零元";  
		    //System.out.println(moneyNum);  
		    for(len--;len>=0;len--){  
		        res=ChineseUnit[i++]+res;  
		        int num=Integer.parseInt(moneyNum.charAt(len)+"");  
		        res=ChineseNum[num]+res;  
		    }  
		    return res.replaceAll("零[拾佰仟]", "零")  
		            .replaceAll("零+亿", "亿").replaceAll("零+万", "万")  
		            .replaceAll("零+元", "元").replaceAll("零+", "零");  
		              
		}  
		/** 
		 * 整数位支持12位,到仟亿 
		 * 支持到小数点后3位,如果大于3位,那么会四舍五入到3位 
		 * @throws Exception  
		 * */  
		public static String arabNumToChineseRMB(double moneyNum) throws Exception{  
		    String res="";  
		    String money=String.format("%.3f",moneyNum);  
		    //System.out.println(money);  
		    int i=0;  
		    if(moneyNum==0.0)  
		        return "零元";  
		    String inte = money.split("\\.")[0];  
		    int deci=Integer.parseInt(money.split("\\.")[1].substring(0, 3));  
		    while(deci>0){  
		        res=ChineseUnit[i++]+res;  
		        res=ChineseNum[deci%10]+res;  
		        deci/=10;  
		    }  
		    res=res.replaceAll("零[里分角]", "零");  
		    if(i<3)  
		        res="零"+res;  
		    res=res.replaceAll("零+", "零");  
		    if(res.endsWith("零"))  
		        res=res.substring(0, res.length()-1);  
		    return arabNumToChineseRMB(inte)+res;  
		}  

}
